package com.teradata.config;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;

@Component
public class AsyncTask {

    public static Random random =new Random();

    /**
     * @Async所修饰的函数不要定义为static类型，否则异步调用不会生效
     *
     * 这里通过返回Future<T>来返回异步调用的结果，实现异步回调
     */
    @Async
    public Future<String> task1() throws InterruptedException {
        System.out.println("task1 begin");
        long begin = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        System.out.println("task1 end " + (System.currentTimeMillis() - begin));
        return new AsyncResult<String>("task1 is done!");
    }

    @Async
    public Future<String> task2() throws InterruptedException {
        System.out.println("task2 begin");
        long begin = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        System.out.println("tasl2 end " + (System.currentTimeMillis() - begin));
        return new AsyncResult<String>("task2 is done!");
    }

    @Async
    public Future<String> task3() throws InterruptedException {
        System.out.println("task3 begin");
        long begin = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        System.out.println("task3 end " + (System.currentTimeMillis() - begin));
        return new AsyncResult<String>("task3 is done!");
    }
}